import React from 'react';
import { List } from 'antd-mobile'
import ReactDOM from 'react-dom';
import QueueAnim from 'rc-queue-anim';

import { isParent } from '../../../utils/crmUtils';

import './index.sass';

class Picker extends React.Component {
  constructor(props) {
    super(props);

      const v = new Set(props.value);
      let arr = [];
      props.data.map(item => {
        if(v.has(item.value)){
          arr.push(item.label)
        }
    })

    this.state = {
      visible: props.visible,
      value: props.value ? [...props.value] : [],
      labels: arr.length > 0 ? arr.join(',') : props.placeholder || '请选择',
    };
    // console.log('vvv', props.title, props.value);
  }
  _container = null;
  _content = null;
  addModalContainer() {
    if (this._container === null) {
      this._container = document.createElement('div');
      this._container.className = 'crm-mobile-picker-container';
      document.body.appendChild(this._container);
      this._container.style.display='none';
    }
  }

  renderContent = () => {
    ReactDOM.unstable_renderSubtreeIntoContainer(
      this,
      // <QueueAnim>
        <Content
          nodeRef={ref => (this._content = ref)}
          key={1}
          title={this.props.title}
          onChange={this.onChange}
          rightContent={this.props.rightContent}
          cancel={() => {
            this.setState({value: this.props.value});
            this.removeModal();
          }}
          value={this.state.value}
          onOk={this.onChange}
          className={this.props.className}
          data={this.props.data}
        >
        </Content>,
      // </QueueAnim>,
      this._container
    );
  };

  onChange = (value) => {
    this.setState({value}, () => {
      const data = this.props.data;
      const v = new Set(value);
      let arr = [];
      data.map(item => {
        if(v.has(item.value)){
          arr.push(item.label)
        }
      })
      this.setState({
        labels: arr.length > 0 ? arr.join(',') : this.props.placeholder || '请选择',
      })
    });

    try {
      this.props.onChange && this.props.onChange(value);
      // this.props.onOk && this.props.onOk(value);
    } catch (error) {
      console.log(error);
    }
    this.removeModal();

  }

  removeModal() {
    if (this.props.onCannel) {
      this.props.onCannel();
    }
    // this.removeTaskClose();
    ReactDOM.unmountComponentAtNode(this._container);
    this._container.style.display='none';
    // document.body.removeChild(this._container);
    // this._container = null;
  }
  showModal() {
    if (this._container) {
      this._container.style.display='block';
      this.renderContent();
      // console.log('renderContent', visible)
    }
  }

  taskCloseContainer = e => {
    // console.log(e.target, this._content, isParent(e.target, this._content));
    if (!isParent(e.target, this._content)) {
      this.removeModal();
    }
  };

  removeTaskClose() {
    this._container.removeEventListener('click', this.taskCloseContainer);
  }

  addTaskClose() {
    this._container.addEventListener('click', this.taskCloseContainer);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      value: nextProps.value,
    })
    // console.log('2',nextProps.visible, nextProps.clickTaskClose);
    // if (nextProps.visible) {
    //   if(this._container){
    //     this._container.style.display='block';
    //   }else{
    //     this.addModalContainer();
    //     this.renderContent();
    //   }
    // }
    // if (nextProps.visible && nextProps.clickTaskClose) {
    //   this.addTaskClose();
    // }
    // this.setState({
    //   visible: nextProps.visible
    // });
  }

  componentDidUpdate() {}

  componentDidMount() {
    // if (this.props.visible) {
    this.addModalContainer();
      // this.showModal();
    // }
    if (this.props.clickTaskClose) {
      this.addTaskClose();
    }
    this.renderContent();
  }
  render() {
    return <div onClick={() => {
      this.setState({visible: true}, () => {this.showModal()})}
    }>
    {
      // this.props.children
    }
      <List.Item extra={this.state.labels} arrow="down">{this.props.children}</List.Item>
    </div>;
  }
}

class Content extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      value: new Set(props.value || []),
    }
  }

  onClick = (item, checked) => {
    let {value} = this.state;
    if(checked){
      value.add(item.value);
    }else{
      value.delete(item.value);
    }
    this.setState({value});
  }

  onOk = () => {
    const {value} = this.state;
    this.props.onOk(Array.from(value));
  }

  renderItems = () => {
    const {value} = this.state;
    const {data} = this.props;
    let items = [];
    data.map((item, index) => {
      // console.log(value, item.value, value.has(item.value))
      items.push( <PickItem onClick={(checked) => this.onClick(item, checked) } checked={value.has(item.value)} key={`picker-item-${index}`}>
          {item.label}
      </PickItem> )
    })
    return items;
  }
  render() {
    const { className } = this.props;
    const items = this.renderItems();
    return (
      <div
        ref={node => this.props.nodeRef(node)}
        className={`crm-mobile-picker-content ${className || ''}`}
        style={{
          bottom: 0,
        }}
      >
        <div className="crm-mobile-picker-content-header">
          <div onClick={this.props.cancel} className='crm-mobile-picker-content-header-cannel'>取消</div>
          <div className='crm-mobile-picker-content-header-title'>{this.props.title}</div>
          <div onClick={this.onOk} className='crm-mobile-picker-content-header-ok'>完成</div>
        </div>
        <div className="crm-mobile-picker-content-center">{items}</div>
      </div>
    );
  }
}

class PickItem extends React.Component{
  constructor(props) {
    super(props);
    this.state={
      checked: props.checked === undefined ? false : props.checked,
    }
    // console.log(props.checked, props.children)
  }
  render() {
    return (
      <div 
        onClick={() => {
          this.setState({checked: !this.state.checked}, () => {
            this.props.onClick && this.props.onClick(this.state.checked)
          });
          
        }} 
        className={`crm-mobile-picker-item ${this.state.checked ? 'crm-mobile-picker-item-checked' : ''}`}
      >
        {this.props.children}
        <i className='crmiconfont crmicon-dui crm-mobile-picker-item-checked-icon' />
      </div>
    );
  }
}

export default Picker;
